import hashlib
import json
import os
import re
import subprocess
import sys

from lxml import etree
import requests
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import QApplication, QWidget, QTableWidget, QHeaderView, QDesktopWidget, QLineEdit, QPushButton, \
    QHBoxLayout, QVBoxLayout, QTableWidgetItem


class Download_tieba_text(QThread):
    # 自定义一个信号
    signal = pyqtSignal(list)

    def __init__(self, html_url):
        super().__init__()
        self.html_url = html_url

    def run(self):
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
            "Cookie": "BIDUPSID=5A6AACB772E92F35CFD50B4F51F2C8FF; PSTM=1562768327; TIEBA_USERTYPE=b9c40c8519d9d4b6875429a4; bdshare_firstime=1575876730706; BAIDUID=5A6AACB772E92F35CFD50B4F51F2C8FF:SL=0:NR=10:FG=1; TIEBAUID=d96b8929f2dc525865d1d2f1; MCITY=-277%3A; H_WISE_SIDS=148077_156537_159077_158360_156286_150775_159610_148867_159881_154738_153629_160470_159530_160443_150772_151493_153065_127969_154413_154174_155331_158528_150346_146734_158746_152572_131424_159255_128701_159284_160105_107319_158054_157012_154190_157947_155344_155255_159954_157790_144966_159949_154213_157814_139882_158643_156849_159594_155930_157965_147551_156710_158415_154639_159156_154309_159546_159074_110085_157006; IS_NEW_USER=d628139f9da556103cdb6755; CLIENTWIDTH=375; CLIENTHEIGHT=812; Hm_lvt_7d6994d7e4201dd18472dd1ef27e6217=1604404307; SEENKW=%E6%B4%9B%E6%9D%89%E7%9F%B6%E6%B9%96%E4%BA%BA%23lol; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; H_PS_PSSID=1458_32854_33061_31253_33098_33101_32938_33145_32846_26350; Hm_lvt_98b9d8c2fd6608d564bf2ac2ae642948=1605750064,1605771774,1606207759,1606350179; st_key_id=17; wise_device=0; delPer=0; PSINO=5; BAIDUID_BFESS=247F33645BD149C2DD3124B767877443:FG=1; Hm_lpvt_98b9d8c2fd6608d564bf2ac2ae642948=1606360782; st_data=bdeecc06c72c6e747fe5d2faddd14d2f3d7cb81b96aa9f46910e37915310ee09bac5ebfae1407d4bd74198db8f318abc17fd4993d344b9e363238f1d2cc11ebcf7858df986d55d1cad3cd8cc950cf0407d813d93c802e3dd67bf7009fc20ff2a6fbe1d7ff2d25b1260555b6666de41bdc5a55b69dff97d1285499b39421450d4; st_sign=a4b1c666"
        }

        url = self.html_url

        r = requests.get(url=url, headers=headers, allow_redirects=False)
        # 获取html页面信息
        html_content = r.content.decode()
        html_content = re.sub(r"<!--", "", html_content)

        html_content = re.sub(r"--!>", "", html_content)

        html = etree.HTML(html_content)

        # 提取要爬取的内容

        # 标题
        title = html.xpath('//ul[@id="thread_list"]/li/div/div[2]/div[1]/div[1]/a/text()')
        # 内容
        content = html.xpath('//ul[@id="thread_list"]/li/div/div[2]/div[2]/div[1]/div[1]/text()')
        # 回复数量
        picture_url = html.xpath('//ul[@id="thread_list"]/li/div/div[1]/span/text()')
        # 时间
        last_time = html.xpath('//span[@class="threadlist_reply_date pull_right j_reply_data"]/text()')

        for i in range(len(title)):
            data_list = []
            data_list.append(title[i])
            data_list.append(content[i])
            data_list.append(last_time[i])
            data_list.append(picture_url[i])
            data_list.append(i)

            self.signal.emit(data_list)


class OpenFileBtn(QPushButton):
    def __init__(self, file_name, name="搜索"):
        super().__init__(name)
        self.clicked.connect(self.click_btn)
        self.file_name = file_name

    def click_btn(self):
        pass


class Tiebaget(QWidget):
    def __init__(self):
        super().__init__()
        self.__init_ui()

    def __init_ui(self):
        self.table = QTableWidget(0, 4)  # 4行3列
        self.table.setHorizontalHeaderLabels(['标题', '内容', '时间', '回复数'])

        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Interactive)
        self.table.horizontalHeader().setSectionResizeMode(2, QHeaderView.Interactive)
        self.table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Interactive)

        # 设置垂直布局
        layout = QVBoxLayout()
        layout.addWidget(self.table)

        self.setLayout(layout)


class Mywindow(QWidget):
    # 自定义一个信号
    db_signal = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.__init_ui()

    def __init_ui(self):
        # 调整窗口位置、大小、要显示的控件
        self.resize(1680, 780)
        self.setWindowTitle('百度贴吧捕获器')
        # 将窗口显示到屏幕中央
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()  # 获取窗口坐标系
        left = (screen.width() - size.width()) / 2
        top = (screen.height() - size.height()) / 2
        self.move(left, top)
        # 创建一个输入框
        self.tieba_input = QLineEdit()
        # 创建一个按钮
        self.search_btn = QPushButton("搜索")
        #  给按钮设置信号绑定槽函数
        self.search_btn.clicked.connect(self.click_handle)
        # 创建一个水平布局器
        h_layout = QHBoxLayout()
        # 将输入框、按钮添加到水平布局器
        h_layout.addWidget(self.tieba_input)
        h_layout.addWidget(self.search_btn)
        # 创建一个垂直布局容器
        v_layout = QVBoxLayout()
        v_layout.addLayout(h_layout)
        self.download_history = Tiebaget()
        v_layout.addWidget(self.download_history)
        # 将水平布局器添加到本widget
        self.setLayout(v_layout)

    def click_handle(self):
        """点击开始爬取贴吧内容"""
        # 获取输入框中贴吧名，
        self.tieba_name = self.tieba_input.text()
        # 拼接URL  https://tieba.baidu.com/f?kw=
        self.html_url = 'https://tieba.baidu.com/f?kw=' + self.tieba_name

        if not self.html_url:
            return

        self.login_thread = Download_tieba_text(self.html_url)
        # 将要创建的子线程类中的信号进行绑定
        self.login_thread.signal.connect(self.update_table_data)
        # 让子线程开始工作
        self.login_thread.start()

    def update_table_data(self, param):
        print(param)
        row = param[-1]
        table_row_num = self.download_history.table.rowCount()
        self.download_history.table.setRowCount(table_row_num + 1)

        self.download_history.table.setItem(row, 0, QTableWidgetItem(param[0]))
        self.download_history.table.setItem(row, 1, QTableWidgetItem(param[1]))
        self.download_history.table.setItem(row, 2, QTableWidgetItem(param[2]))
        self.download_history.table.setItem(row, 3, QTableWidgetItem(param[3]))
        # self.download_history.table.setCellWidget(row, 2, OpenFileBtn(one_download_history['video_title']))


if __name__ == '__main__':
    app = QApplication(sys.argv)

    w = Mywindow()

    w.show()

    app.exec()
